package com.gcxy.config.exception;

import com.gcxy.utils.R;
import com.gcxy.utils.ResultCondeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @auther:韦林鹏 `*@since:2023/12/14 09 35
 * @description:
 */
@ControllerAdvice
@Slf4j
public class BasicExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R errorHandler(MethodArgumentNotValidException e){
//        BindingResult bindingResult=exception.getBindingResult();
        String message="";
//        String message=bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        for(ObjectError s:e.getAllErrors()){
            message+="["+s.getDefaultMessage()+"]";
        }
        System.out.println(message);
        return R.Failed(ResultCondeEnum.REQUEST_PARAM_ERROR.getCode(),message);
    }
    /**
     * 处理全局异常""
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public R errorHandler(Exception exception){
        return R.Failed(ResultCondeEnum.SYSTEM_EXCEPTION.getCode(), exception.getMessage());
    }
}
